package com.cskt.shiro;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JwtUtil {
    //过期时间为两小时
    private static final long EXPRIE_TIME = 2*60*60*1000;
    /**
     * 校验用户名和密码
     */
    public static boolean verify(String token, String username, String secret){

        try{
            Algorithm algorithm = Algorithm.HMAC512(secret);
            JWTVerifier jwtVerifier = JWT.require(algorithm)
                    .withClaim("usname", username)
                    .build();
            jwtVerifier.verify(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public static String getUsername(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").toString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成JWTToken
     * @param username
     * @param secret
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String sign(String username, String secret) throws
            UnsupportedEncodingException{
        //过期时间
        Date date = new Date(System.currentTimeMillis() + EXPRIE_TIME);
        //指定加密规则
        Algorithm algorithm = Algorithm.HMAC512(secret);
        //附带自定义负载
       return JWT.create()
                .withClaim("username",username)
                .withExpiresAt(date)
                .sign(algorithm);
    }
}
